package cn.findviewbydream.service.impl;

import cn.findviewbydream.dao.UserMapper;
import cn.findviewbydream.entity.UserEntity;
import cn.findviewbydream.enums.SessionEnum;
import cn.findviewbydream.enums.UserEnum;
import cn.findviewbydream.exception.UserException;
import cn.findviewbydream.service.UserService;
import cn.findviewbydream.utils.CheckNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**********************************
 * 工程：cn.findviewbydream.service.impl
 * 作者：白雨濃 evil
 * 时间：17-6-1 下午10:09
 * 邮箱：evilbai@foxmail.com
 * 内容：用户类操作，包含注册，登录等功能
 **********************************/
@Service
public class UserServiceImpl implements UserService
{
    private final UserMapper mapper;

    @Autowired
    public UserServiceImpl(UserMapper mapper)
    {
        this.mapper = mapper;
    }


    @Override
    public UserEntity login(String userId, String password, HttpSession session)
    {
        UserEntity entity = mapper.selectUser(userId);

        if (entity == null)
            throw new UserException(UserEnum.NO_USER);

        if (!entity.getPassword().equals(password))
            throw new UserException(UserEnum.ERROR_PASSWORD);

        /*更新最后登录时间*/
        int count = mapper.updateUserLastLoginTime(userId);

        /*如果更新返回的行数不为1，则意味着失败，抛出未知错误*/
        if (count != 1)
            throw new UserException(UserEnum.UNKNOWN_ERROR);

        /*剔除密码*/
        entity.setPassword(null);
        /*将用户实体存入session*/
        session.setAttribute(SessionEnum.USER.getKey(), entity);

        return entity;
    }

    @Override
    public UserEntity register(UserEntity entity)
    {
        try
        {
            mapper.insertUser(entity);
        }
        catch (Exception e)
        {
            /*主键重复，表示表中已经有了该id*/
            if (e instanceof DuplicateKeyException)
                throw new UserException(UserEnum.HAVE_USERID);

            /*非以上错误,则抛出未知异常*/
            throw new UserException(UserEnum.UNKNOWN_ERROR);
        }

        return mapper.selectUserNoPassword(entity.getUserId());
    }
}
